import { Module } from 'vuex'
import type { ILoginState } from './type'
import type { IRootState } from '../type'
import { accountLoginRequest, getUserInfoRequest, getRoleMenusRequest } from '@/service/login/login'
import LocalCache from '@/utils/LocalCache'
import router from '@/router'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state: () => ({
    userInfo: LocalCache.getCache('userInfo') || {},
    token: LocalCache.getCache('token') || '',
    userMenus: []
  }),
  actions: {
    async accountLoginAction({ commit }, payload: any) {
      const account = {
        name: payload.username,
        password: payload.password
      }
      const isSavePassword = payload.isSavePassword
      const res: any = await accountLoginRequest(account)
      // 如果有请求响应code为0 那么认定这个登录请求是成功的
      if (res.code === 0) {
        // 如果需要记住密码
        if (isSavePassword) {
          LocalCache.setCache('username', account.name)
          LocalCache.setCache('password', account.password)
        } else {
          LocalCache.removeCache('username')
          LocalCache.removeCache('password')
        }
        // 保存token
        const token = res.data.token
        commit('saveToken', token)
        // 获取用户信息
        const id = res.data.id
        const userInfoRes: any = await getUserInfoRequest(id)

        if (userInfoRes.code === 0) {
          const userInfo = userInfoRes.data
          commit('saveUserInfo', userInfo)
          // 获取角色菜单
          const roleId = userInfo.role.id
          const roleMenuRes: any = await getRoleMenusRequest(roleId)
          if (roleMenuRes.code === 0) {
            commit('saveMenus', roleMenuRes.data)
          }
          router.push('/main')
        }
      }
    }
  },
  mutations: {
    saveToken(state, token: string) {
      LocalCache.setCache('token', token)
      state.token = token
    },
    saveUserInfo(state, user: any) {
      LocalCache.setCache('userInfo', user)
      state.userInfo = user
    },
    saveMenus(state, menus: []) {
      LocalCache.setCache('menus', menus)
      state.userInfo = menus
    }
  }
}

export default loginModule
